<script lang="ts" setup>
import { transformFormSchema, useAddEditForm, useAddEditFormModal } from '#/hooks/useAddEditForm'
import { useLocales } from '#/hooks/useLocales'
import { $t } from '@vben/locales'
import { isEmpty } from '@vben/utils'
import { computed } from 'vue'
import { getAddEditFormSchema } from '../data/AddEditFrom'
import { PageApi } from '../use/api'
import { PAGE_NAME } from '../use/config'

defineOptions({
    name: 'FormModelMenu'
})

const props = withDefaults(
    defineProps<{
        modalType?: 'drawer' | 'modal'
    }>(),
    {
        modalType: 'modal'
    }
)

defineEmits(['success'])
const { isLocaleZH } = useLocales()
const { Form, formApi, formTitle, setRowId, setViewMode } = useAddEditForm({
    title: PAGE_NAME,
    onAddSubmit(values) {
        return PageApi.add(values)
    },
    onEditSubmit({ values, rowId }) {
        return PageApi.edit({
            id: rowId,
            ...values
        })
    },
    useFormParams: {
        commonConfig: {
            labelWidth: isLocaleZH.value ? 100 : 150
        }
    }
})

const { Modal, modalApi } = useAddEditFormModal({
    modalType: props.modalType,
    formApi,
    useModalParams: {
        class: 'w-[1000px]'
    },
    onOpen({ treeData, record, pid, isViewMode = false }) {
        setViewMode(isViewMode)
        if (isViewMode) {
            modalApi.setState({
                showConfirmButton: false,
                cancelText: $t('common.close')
            })
        } else {
            modalApi.setState({
                showConfirmButton: true,
                cancelText: $t('common.cancel')
            })
        }
        setRowId(record?.id ?? null)
        const treeData2 = treeData
            ? [
                  {
                      id: 0,
                      title: $t('page.system.children.menu.children.root')
                  },
                  ...treeData
              ]
            : []

        const schema = getAddEditFormSchema({
            formApi,
            treeData: treeData2,
            rowId: computed(() => record?.id)
        })

        formApi.setState({
            // 更新表单数据
            schema: isViewMode ? transformFormSchema(schema) : schema
        })

        // 更新树结构 打开已选择的节点
        formApi.updateSchema([
            {
                fieldName: 'pid',
                defaultValue: pid,
                componentProps: {
                    treeDefaultExpandedKeys: isEmpty(pid) ? [] : [pid]
                }
            }
        ])

        // 回填表单数据
        if (record) {
            formApi.setValues(record)
        }
    }
})
</script>
<template>
    <Modal :title="formTitle">
        <Form />
    </Modal>
</template>
